package com.ilink.groundservice.service.impl.Tool;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.groundservice.entity.PO.Tool.AiXTool;
import com.ilink.groundservice.entity.VO.AiX.AiXToolResponse;
import com.ilink.groundservice.mapper.Tool.AiXToolMapper;
import com.ilink.groundservice.mapper.AiX.AiXTagConnectMapper;
import com.ilink.groundservice.service.Tool.AiXToolService;
import com.ilink.groundservice.service.Tool.AiXToolUsageRecordService;
import com.ilink.ilinkapi.dto.ground.AiX.AiXToolFilterRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXToolInsertRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXToolUpdateRequest;
import com.ilink.ilinkcommon.exception.BizIllegalException;
import com.ilink.ilinkcommon.utils.BeanUtils;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class AiXToolServiceImpl implements AiXToolService {

    private final AiXToolMapper toolMapper;
    private final AiXToolUsageRecordService usageRecordService;
    private final OssService ossService;
    private final AiXTagConnectMapper tagConnectMapper;

    @Override
    public IPage<AiXToolResponse> getToolList(AiXToolFilterRequest request) {
        Page<AiXToolResponse> page = new Page<>(request.getPage(), request.getSize());
        // 如果有标签筛选，使用标签筛选方法；否则使用原有方法
        IPage<AiXToolResponse> result;
        if (request.getTag() != null && !request.getTag().trim().isEmpty()) {
            result = toolMapper.selectToolPageByTag(page, request);
        } else {
            result = toolMapper.selectToolPage(page, request);
        }
        
        // 为每个工具设置标签列表
        result.getRecords().forEach(tool -> {
            List<String> tags = toolMapper.selectToolTags(tool.getToolId());
            tool.setTags(tags);
        });
        
        return result;
    }

    @Override
    public AiXToolResponse getToolById(Long toolId) {
        if (toolId == null) {
            throw new BizIllegalException("工具ID不能为空");
        }
        
        AiXToolResponse response = toolMapper.selectToolById(toolId);
        if (response == null) {
            throw new BizIllegalException("工具不存在");
        }
        
        // 设置标签列表
        List<String> tags = toolMapper.selectToolTags(toolId);
        response.setTags(tags);
        
        return response;
    }

    @Override
    @Transactional
    public Long insertTool(AiXToolInsertRequest request) {
        if (request == null) {
            throw new BizIllegalException("请求参数不能为空");
        }
        
        AiXTool tool = BeanUtils.copyBean(request, AiXTool.class);
        
        // 使用雪花算法生成ID
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(8, 1);
        tool.setToolId(idGenerator.nextId());
        
        tool.setUsageCount(0);
        tool.setCreatedAt(LocalDateTime.now());
        tool.setUpdatedAt(LocalDateTime.now());
        
        // 处理图标上传
        if (request.getToolIcon() != null && !request.getToolIcon().isEmpty()) {
            String iconUrl = ossService.uploadFileAndGetUrl(request.getToolIcon(), "study-square-migrate", "tool/icon_" + System.currentTimeMillis() + "_" + request.getToolIcon().getOriginalFilename());
            tool.setToolIcon(iconUrl);
        }
        
        int result = toolMapper.insert(tool);
        if (result <= 0) {
            throw new BizIllegalException("工具创建失败");
        }
        
        return tool.getToolId();
    }

    @Override
    @Transactional
    public void updateTool(AiXToolUpdateRequest request) {
        if (request == null || request.getToolId() == null) {
            throw new BizIllegalException("请求参数不能为空");
        }
        
        AiXTool existingTool = toolMapper.selectById(request.getToolId());
        if (existingTool == null) {
            throw new BizIllegalException("工具不存在");
        }
        
        AiXTool tool = BeanUtils.copyBean(request, AiXTool.class);
        tool.setUpdatedAt(LocalDateTime.now());
        
        // 处理图标上传
        if (request.getToolIcon() != null && !request.getToolIcon().isEmpty()) {
            String iconUrl = ossService.uploadFileAndGetUrl(request.getToolIcon(), "study-square-migrate", "tool/icon_" + System.currentTimeMillis() + "_" + request.getToolIcon().getOriginalFilename());
            tool.setToolIcon(iconUrl);
        }
        
        int result = toolMapper.updateById(tool);
        if (result <= 0) {
            throw new BizIllegalException("工具更新失败");
        }
    }

    @Override
    @Transactional
    public void deleteTool(Long toolId) {
        if (toolId == null) {
            throw new BizIllegalException("工具ID不能为空");
        }
        
        AiXTool tool = toolMapper.selectById(toolId);
        if (tool == null) {
            throw new BizIllegalException("工具不存在");
        }
        
        int result = toolMapper.deleteById(toolId);
        if (result <= 0) {
            throw new BizIllegalException("工具删除失败");
        }
    }

    @Override
    @Transactional
    public void updateToolIcon(MultipartFile file, Long toolId) {
        if (file == null || file.isEmpty()) {
            throw new BizIllegalException("图标文件不能为空");
        }
        if (toolId == null) {
            throw new BizIllegalException("工具ID不能为空");
        }
        
        AiXTool tool = toolMapper.selectById(toolId);
        if (tool == null) {
            throw new BizIllegalException("工具不存在");
        }
        
        String iconUrl = ossService.uploadFileAndGetUrl(file, "study-square-migrate", "tool/icon_" + System.currentTimeMillis() + "_" + file.getOriginalFilename());
        tool.setToolIcon(iconUrl);
        tool.setUpdatedAt(LocalDateTime.now());
        
        int result = toolMapper.updateById(tool);
        if (result <= 0) {
            throw new BizIllegalException("工具图标更新失败");
        }
    }

    @Override
    public List<AiXToolResponse> getPopularTools(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        List<AiXToolResponse> results = toolMapper.selectPopularTools(limit);
        
        // 为每个工具设置标签列表
        results.forEach(tool -> {
            List<String> tags = toolMapper.selectToolTags(tool.getToolId());
            tool.setTags(tags);
        });
        
        return results;
    }

    @Override
    public List<String> getAllToolTags(Long areaId) {
        return tagConnectMapper.getAllToolTags(areaId);
    }

    @Override
    public List<String> getToolTags(Long areaId) {
        return tagConnectMapper.getToolTags(areaId, 8);
    }

    @Override
    @Transactional
    public String launchTool(Long toolId, String userId, String inputConfig) {
        if (toolId == null) {
            throw new BizIllegalException("工具ID不能为空");
        }
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        // 检查工具是否存在
        AiXToolResponse tool = getToolById(toolId);
        if (!tool.getIsActive()) {
            throw new BizIllegalException("工具未激活");
        }
        
        // 生成会话ID
        String sessionId = UUID.randomUUID().toString();
        
        // 创建使用记录
        usageRecordService.createUsageRecord(toolId, userId, inputConfig, sessionId, "127.0.0.1");
        
        // 增加使用次数
        toolMapper.incrementUsageCount(toolId);
        
        // 实际启动工具的逻辑（这里是模拟）
        log.info("启动工具: toolId={}, userId={}, sessionId={}", toolId, userId, sessionId);
        
        return sessionId;
    }

    @Override
    @Transactional
    public void stopTool(String sessionId, String userId) {
        if (sessionId == null) {
            throw new BizIllegalException("会话ID不能为空");
        }
        
        // 更新使用记录状态
        usageRecordService.updateUsageRecord(sessionId, "stopped", null, null);
        
        log.info("停止工具: sessionId={}, userId={}", sessionId, userId);
    }

    @Override
    public String getToolStatus(String sessionId) {
        if (sessionId == null) {
            throw new BizIllegalException("会话ID不能为空");
        }
        
        // 这里应该查询实际的工具运行状态
        // 简化实现，返回模拟状态
        return "running";
    }
} 